package com.loan.market.ui

import android.content.Intent
import android.net.Uri
import android.view.View
import android.view.View.OnClickListener
import android.widget.FrameLayout
import android.widget.LinearLayout.LayoutParams
import androidx.core.view.updateLayoutParams
import com.loan.market.R
import com.loan.market.base.BaseBindingFragment
import com.loan.market.bean.User
import com.loan.market.bean.UserInfo
import com.loan.market.databinding.DialogCustomerBinding
import com.loan.market.databinding.FragmentMeBinding
import com.loan.market.http.ApiService
import com.loan.market.http.getHttpMap
import com.loan.market.http.request
import com.loan.market.util.*

class MeFragment : BaseBindingFragment<FragmentMeBinding>(), OnClickListener {

    override fun getViewBinding(): FragmentMeBinding {
        return FragmentMeBinding.inflate(layoutInflater)
    }

    override fun initUi() {
        binding.llHeader.updateLayoutParams<LayoutParams> { topMargin = requireContext().getStatusBarHeight() }
        binding.ivHeader.updateLayoutParams<FrameLayout.LayoutParams> { topMargin = 88f.dp2px() + requireActivity().getStatusBarHeight() }
        binding.ivTerms.setOnClickListener {
            startActivity(Intent(requireActivity(), TermsActivity::class.java))
        }
    }

    override fun initEvent() {
        binding.llEdit.setOnClickListener(this)
        binding.llPromotions.setOnClickListener(this)
        binding.llSetting.setOnClickListener(this)
        binding.llContact.setOnClickListener(this)
    }

    override fun initData() {
        getConfig {
            binding.tvUsername.text = it.userName
            binding.stepView.setStep(0)
        }
    }

    override fun onResume() {
        super.onResume()
        if (UserUtil.isLogin()) {
            val user = SPUtil.getObject<User>("user")
            val id = user?.userId ?: ""
            if (id.length > 14) {
                binding.tvId.text = getString(R.string.id) + "****" + id.substring(id.length - 10, id.length)
            } else {
                binding.tvId.text = getString(R.string.id) + id
            }
            val phone = user?.phone ?: ""
            if (phone.length >= 4) {
                binding.tvPhone.text = getString(R.string.phone) + "****" + phone.substring(phone.length - 4, phone.length)
            } else {
                binding.tvPhone.text = getString(R.string.phone) + phone
            }
            http {
                var complete = 0
                val map = getHttpMap(501)
                request<UserInfo>(map, ApiService.path4)?.let {
                    if (it.name.isNotEmpty()) {
                        binding.tvUsername.text = it.name
                        complete++
                    }
                    if (it.gender > 0) complete++
                    if (it.marital > 0) complete++
                    if (it.education > 0) complete++
                    if (it.birthDate.isNotEmpty()) complete++
                    if (it.workIndustry.isNotEmpty()) complete++
                    if (it.addressProvince.isNotEmpty() && it.addressCity.isNotEmpty()) complete++
                    binding.stepView.setStep(((complete * 10f / 7) + 0.5f).toInt())
                }
            }
        } else {
            initData()
            binding.tvId.text = getString(R.string.id) + "-"
            binding.tvPhone.text = getString(R.string.phone) + "-"
        }
    }

    override fun onClick(v: View) {
        if (!UserUtil.isLogin()) {
            startActivity(Intent(requireActivity(), LoginActivity::class.java))
            return
        }
        when (v) {
            binding.llPromotions -> {
                startActivity(Intent(requireActivity(), PromotionsActivity::class.java))
            }

            binding.llEdit -> {
                startActivity(Intent(requireActivity(), EditInfoActivity::class.java))
            }

            binding.llSetting -> {
                startActivity(Intent(requireActivity(), SettingActivity::class.java))
            }

            binding.llContact -> {
                getConfig { config ->
                    val bind = DialogCustomerBinding.inflate(layoutInflater)
                    val dialog = requireActivity().showDialog(bind.root)
                    if (config.serviceTel.isBlank()) {
                        bind.tvPhone.visibility = View.GONE
                    }
                    bind.tvPhone.text = "Teléfono: ${config.serviceTel}"
                    bind.tvEmail.text = "Correo: ${config.serviceEmail}"
                    bind.tvPhone.setOnClickListener {
                        dialog.dismiss()
                        val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + config.serviceTel))
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        startActivity(intent)
                    }
                    bind.tvEmail.setOnClickListener {
                        dialog.dismiss()
                        if (config.serviceEmail.isBlank()) return@setOnClickListener
                        val intent = Intent(Intent.ACTION_SENDTO)
                        intent.setData(Uri.parse("mailto:"));
                        intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(config.serviceEmail)) // 收件人
                        startActivity(intent)
                    }
                    bind.btnConfirm.setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }
        }
    }
}